import { Injectable } from '@nestjs/common';
import { SystemStatsDto, AdminRecommendedPlaylistDto } from './admin.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../user/user.entity';
import { Song } from '../song/song.entity';
import { Album } from '../album/album.entity';
import { Playlist } from '../playlist/playlist.entity';

@Injectable()
export class AdminService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    @InjectRepository(Song) private songRepository: Repository<Song>,
    @InjectRepository(Album) private albumRepository: Repository<Album>,
    @InjectRepository(Playlist)
    private playlistRepository: Repository<Playlist>,
  ) {}

  // 获取系统概览统计信息
  async getSystemStats(): Promise<SystemStatsDto> {
    // 获取各项统计数据
    const totalUsers = await this.userRepository.count();
    const totalSongs = await this.songRepository.count({
      where: { isDeleted: false },
    });
    const totalAlbums = await this.albumRepository.count();
    const totalPlaylists = await this.playlistRepository.count();

    // 可以添加获取最近活动的逻辑
    const recentActivities = [];

    return {
      totalUsers,
      totalSongs,
      totalAlbums,
      totalPlaylists,
      recentActivities,
    };
  }

  // 获取推荐歌单列表
  async getRecommendedPlaylists(): Promise<AdminRecommendedPlaylistDto[]> {
    const query = this.playlistRepository
      .createQueryBuilder('playlist')
      .leftJoinAndSelect('playlist.createdBy', 'createdBy')
      .leftJoinAndSelect('playlist.songs', 'songs')
      .where('playlist.isOfficial = :isOfficial', { isOfficial: 1 })
      // .orWhere('playlist.isPublic = :isPublic', { isPublic: true })
      .orderBy('playlist.recommendLevel', 'DESC')
      .addOrderBy('playlist.likes', 'DESC')
      .take(20); // 限制返回20个歌单
    const playlists = await query.getMany();
    // 映射为DTO返回
    return playlists.map((playlist) => ({
      id: playlist.id,
      name: playlist.name,
      description: playlist.description,
      coverImageUrl: playlist.coverImageUrl,
      createdBy: {
        id: playlist.createdBy.id,
        username: playlist.createdBy.username,
      },
      songCount: playlist.songs.length,
      likes: playlist.likes,
      isPublic: playlist.isPublic,
      isOfficial: playlist.isOfficial,
      recommendLevel: playlist.recommendLevel,
      createdAt: playlist.createdAt,
      updatedAt: playlist.updatedAt,
    }));
  }

  // 其他管理员相关的业务逻辑可以在这里添加
}
